/**
 * 手写Promise
 */

class HD{
  static PENDING = 'pending'
  static FULFILLED = 'fulfilled'
  static REJECTED = 'rejected'
  constructor(exector){
    this.status = HD.PENDING
    this.value = null
    this.callbacks = []
    try {
      exector(this.resolve.bind(this), this.reject.bind(this)) 
    } catch (error) {
      this.reject(error)
    }
  }

  resolve(value){
    if(this.status === HD.PENDING){
      this.status = HD.FULFILLED
      this.value = value

      this.callbacks.map(callback => {
        callback.onfulfilled(value)
      })
      // console.log(this.value);
    }
  }
  reject(reason){
    if(this.status=== HD.PENDING){
      this.status = HD.REJECTED
      this.value = reason
      this.callbacks.map(callback => {
        callback.onrejected(reason)
      })
    }
  }
  then(onfulfilled, onrejected) {
    if(typeof onrejected !== 'function'){
      onrejected =() => {}
    }
    if(typeof onfulfilled !== 'function'){
      onfulfilled =() => {}
    }
    if(this.status === HD.FULFILLED){
      setTimeout(() =>{
        try {
          onfulfillen(this.value)
        } catch (error) {
          onrejected(error)
        }
      })
    }
    if(this.status === HD.PENDING){
      this.callbacks.push({
        onfulfilled:value => {
          try {
            onfulfilled(value)
          } catch (error) {
            onrejected(error)
          }
        },
        onrejected: reason => {
          try {
            onrejected(reason)
          } catch (error) {
            onrejected(error)
          }
        }
      })
    }
    if(this.status === HD.REJECTED){
      setTimeout(()=>{
        try {
          onrejected(this.value)
        } catch (error) {
          onrejected(error)
        }
      })
    }
  }
  catch(onrejected){
    if(this.status === HD.REJECTED){
      onrejected(this.value)
    }
  }

}

new Promise((resolve, reject) => {

})